<template>
  <div class="dashboard-container">
    <h2 class="head-big-title">Semak Keluar
      <div style="float: right;margin-right: 7%;cursor: pointer;" @click="$router.push({path:'/Shop/Shopping-Cart'})">
        <svg-icon v-if="tableData.length > 0" icon-class="gouwucheman" style="font-size: 24px;margin-right: 10px;position: relative;bottom: 5px" />
        <svg-icon v-else icon-class="gouwuchekong" style="font-size: 24px;margin-right: 10px;position: relative;bottom: 5px" />
        <p style="display: inline-block;font-size: 14px;"><span>{{ $formatMoneyStr(total) }}</span><span style="display: block;">{{ tableData.length }} barang</span></p>
      </div>
    </h2>
    <el-input
      round
      placeholder="Search"
      v-model="searchProductName"
      @blur="searchProduct"
      prefix-icon="el-icon-search"
      style="width: 92%;margin: 10px 0;"></el-input>
    <Pathnavigation style="margin-left: 3%;"></Pathnavigation>
    <el-card v-if="detailData == {}" shadow="always" :body-style="{ padding: '15px 0 25px 20px' }" style="width: 92%;margin: 0 4%;background-color: white;border-radius: 10px;text-align: left;">
      <h2 class="title">Alamat Bil</h2>
      <p class="two-info"><i class="el-icon-coordinate" />Luqman bin Muhammad Asmin</p>
      <p class="two-info"><i class="el-icon-phone-outline" />+6016 888 8888</p>
      <p class="two-info"><i class="el-icon-location-outline" />No.66, Block Crystal, Jalan 1/19,40150, Petaling Jaya, Selangor,Malaysia</p>
    </el-card>
    <el-card v-else shadow="always" :body-style="{ padding: '15px 0 25px 20px' }" style="width: 92%;margin: 0 4%;background-color: white;border-radius: 10px;text-align: left;">
      <h2 class="title">Alamat Bil<i class="el-icon-edit" style="float: right;margin-right: 32px;cursor:pointer;" @click="editAddress(1)" /></h2>
      <p class="two-info"><svg-icon icon-class="ico_user" style="font-size: 18px;margin-right: 6px;" />{{ detailData.billingAddr.name }}</p>
      <p class="two-info"><svg-icon icon-class="ico_phone" style="font-size: 18px;margin-right: 6px;" />{{ detailData.billingAddr.phoneNumber }}</p>
      <p class="two-info"><svg-icon icon-class="ico_address" style="font-size: 18px;margin-right: 6px;" />
        {{ detailData.billingAddr.streetAddress + ', ' +detailData.billingAddr.regionalAddress + ', ' + detailData.billingAddr.postCode + ', ' + detailData.billingAddr.city + ', ' + detailData.billingAddr.region }}</p>
    </el-card>
    <el-card v-if="detailData == {}" shadow="always" :body-style="{ padding: '15px 0 25px 20px' }" style="width: 92%;margin: 15px 4% 0 4%;background-color: white;border-radius: 10px;text-align: left;">
      <h2 class="title">Alamat Penghantaran</h2>
      <p class="two-info"><i class="el-icon-coordinate" />Luqman bin Muhammad Asmin</p>
      <p class="two-info"><i class="el-icon-phone-outline" />+6016 888 8888</p>
      <p class="two-info"><i class="el-icon-location-outline" />No.66, Block Crystal, Jalan 1/19,40150, Petaling Jaya, Selangor,Malaysia</p>
    </el-card>
    <el-card v-else shadow="always" :body-style="{ padding: '15px 0 25px 20px' }" style="width: 92%;margin: 15px 4% 0 4%;background-color: white;border-radius: 10px;text-align: left;">
      <h2 class="title">Alamat Penghantaran<i class="el-icon-edit" style="float: right;margin-right: 32px;cursor:pointer;" @click="editAddress(2)" /></h2>
      <p class="two-info"><svg-icon icon-class="ico_user" style="font-size: 18px;margin-right: 6px;" />{{ detailData.shopAddr.name }}</p>
      <p class="two-info"><svg-icon icon-class="ico_phone" style="font-size: 18px;margin-right: 6px;" />{{ detailData.shopAddr.phoneNumber }}</p>
      <p class="two-info"><svg-icon icon-class="ico_address" style="font-size: 18px;margin-right: 6px;" />{{ detailData.shopAddr.streetAddress + ', ' +detailData.shopAddr.regionalAddress + ', ' + detailData.shopAddr.postCode + ', ' + detailData.shopAddr.city + ', ' + detailData.shopAddr.region }}</p>
    </el-card>
    <el-card shadow="always" v-if="tableData.length && (tableData.length >0) " :body-style="{ padding: '10px' }" style="width: 92%;margin: 15px 4% 0 4%;background-color: white;border-radius: 10px;">
      <el-table
        :show-header="false"
        :data="tableData"
        style="margin: 0;">
        <el-table-column label="Logo" width="100">
          <template slot-scope="scope">
            <div style="width: 100%;height: 100%;position: relative;">
              <el-image
                style="width: 64px; height: 64px"
                :src="picbase + scope.row.picUrl">
              </el-image>
              <div @click="handleDel(scope.row)" style="width: 26px;height: 26px;position: absolute;bottom: 6px;right: 16px;color: white;background-color: rgba(245,0,3,0.8)">
                <svg-icon icon-class="ico-del" style="margin: 3px;font-size: 20px;"></svg-icon>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center">
          <template slot-scope="scope">
            <p>{{$formatMoneyStr(scope.row.price)}}</p>
            <el-input v-model="scope.row.quantity" @change="changeQuantity(scope.row)"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center">
          <template slot-scope="scope">
            <p>{{$formatMoneyStr(scope.row.total)}}</p>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-card shadow="always" v-if="tableData.length && (tableData.length >0) " :body-style="{ padding: '10px' }" style="width: 92%;margin: 15px 4% 0 4%;background-color: white;border-radius: 10px;">
      <h2 style="font-size: 18px;text-align: left;">Nota Penghantaran</h2>
      <el-input
        style="margin-bottom: 10px;margin-top: 15px;"
        type="textarea"
        :rows="5"
        placeholder="Note"
        v-model="note">
      </el-input>
    </el-card>
    <el-card shadow="always" :body-style="{ padding: '10px' }" style="width: 92%;margin: 15px 4% 0 4%;background-color: white;border-radius: 10px;">
      <div class="total-sum-div">
        <p class="middle-info"><label>Jumlah Kecil</label>: {{$formatMoneyStr(total)}}</p>
        <p class="middle-info"><label>Jumlah Penghantaran</label>: RM 0.00</p>
        <p class="middle-info"><label>Penyesuaian</label>: RM 0.00</p>
        <el-divider></el-divider>
        <p class="middle-info"><label>Jumlah Pesanan</label>{{$formatMoneyStr(total)}}</p>
        <div>
          <el-button type="primary" round v-show="(tableData.length && (tableData.length >0))" style="float: right;margin: 15px 5%;" @click="makePayment" :disabled="isConLoading" :loading="isConLoading">Pastikan Pesanan</el-button>
        </div>
      </div>
    </el-card>
    <el-dialog :visible.sync="showNeedPay" title="Making Payment">
      <FORM method="post" name="ePayment" id="ePayment" ref="ePayment" action="https://payment.ipay88.com.my/ePayment/entry.asp">
        <INPUT type="hidden" name="MerchantCode" :value="payData.MerchantCode"/>
        <INPUT type="hidden" name="PaymentId" :value="payData.PaymentId" />
        <INPUT type="hidden" name="RefNo" :value="payData.RefNo" />
        <INPUT type="hidden" name="Amount" :value="payData.Amount" />
        <INPUT type="hidden" name="Currency" :value="payData.Currency" />
        <INPUT type="hidden" name="ProdDesc" :value="payData.ProdDesc" />
        <INPUT type="hidden" name="UserName" :value="payData.UserName" />
        <INPUT type="hidden" name="UserEmail" :value="payData.UserEmail" />
        <INPUT type="hidden" name="UserContact" :value="payData.UserContact" />
        <INPUT type="hidden" name="Remark" :value="payData.Remark" />
        <INPUT type="hidden" name="Lang" :value="payData.Lang" />
        <INPUT type="hidden" name="SignatureType" :value="payData.SignatureType" />
        <INPUT type="hidden" name="Signature" :value="payData.Signature" />
        <INPUT type="hidden" name="ResponseURL" :value="payData.ResponseURL" />
        <INPUT type="hidden" name="BackendURL" :value="payData.BackendURL" />
        <INPUT type="submit" value="ipay88" name="Submit" class="submit-button"/>
      </FORM>
      <el-button type="primary" @click="dealerNewOrder" :loading="ipayButtonLoading" :disabled="ipayButtonLoading">ipay88</el-button>
    </el-dialog>
    <el-dialog :visible.sync="showConfirmOrderSuess" class="confirm-order-sucess">
      <strong style="display: block;font-size: 21px;line-height: 66px;color: black;">Pesanan dihantar</strong>
      <p style="color: black;">
        Pesanan telah dihantar<br>
        Sila pastikan pesanan dalam rekod<br>
        Terima Kasih
      </p>
      <el-button type="warning" round style="margin: 10px 0 88px 0;" @click="$router.push({path:'/Shop/Query'})">balik kedai</el-button>
    </el-dialog>
    <el-dialog title="Edit" :visible.sync="ShowEditDealerBillingAddress" :fullscreen="false">
      <el-form style="text-align: left;" label-position="top" size="medium" label-width="110px">
        <h2 class="title">Alamat Bil</h2>
        <el-form-item label="Nama: " class="one-hang">
          <el-input v-model="editAddressData.billingAddr.name" @input="changeNew($event)" />
        </el-form-item>
        <el-form-item label="Nombor Telefon: " class="one-hang">
          <el-input v-model="editAddressData.billingAddr.phoneNumber" @input="changeNew($event)" />
        </el-form-item>
        <el-form-item label="Address 1: " class="one-hang">
          <el-input v-model="editAddressData.billingAddr.streetAddress" @input="changeNew($event)" />
        </el-form-item>
        <el-form-item label="Address 2: " class="one-hang">
          <el-input v-model="editAddressData.billingAddr.regionalAddress" @input="changeNew($event)" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button style="text-align: right;margin: 16px 0;" @click="ShowEditDealerBillingAddress = false">Cancel</el-button>
        <el-button type="primary" style="text-align: right;margin: 16px 4% 16px 20px;" @click="saveDataNow(1)">Simpan</el-button>
      </div>
    </el-dialog>
    <el-dialog title="Edit" :visible.sync="ShowEditDealerShoppingAddress" :fullscreen="false">
      <el-form style="text-align: left;" label-position="top" size="medium" label-width="110px">
        <h2 class="title">Alamat Penghantaran</h2>
        <el-form-item label="Nama: " class="one-hang">
          <el-input v-model="editAddressData.shopAddr.name" @input="changeNew($event)" />
        </el-form-item>
        <el-form-item label="Nombor Telefon: " class="one-hang">
          <el-input v-model="editAddressData.shopAddr.phoneNumber" @input="changeNew($event)" />
        </el-form-item>
        <el-form-item label="Address 1: " class="one-hang">
          <el-input v-model="editAddressData.shopAddr.streetAddress" @input="changeNew($event)" />
        </el-form-item>
        <el-form-item label="Address 2: " class="one-hang">
          <el-input v-model="editAddressData.shopAddr.regionalAddress" @input="changeNew($event)" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button style="text-align: right;margin: 16px 0;" @click="ShowEditDealerShoppingAddress = false">Cancel</el-button>
        <el-button type="primary" style="text-align: right;margin: 16px 4% 16px 20px;" @click="saveDataNow(2)">Simpan</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { order_delcartApi, order_querycartApi, order_editcartApi, order_newApi, dealer_query_oneApi, editaddrDealerApi } from '@/api/user'

export default {
  name: 'Activityrecord',
  computed: {
    ...mapGetters([
      'name',
      'role'
    ])
  },
  data() {
    return {
      tableData: [],
      productList: [],
      newOrderData: {},
      searchFormData: {},
      payData: {},
      detailData: {
        shopAddr: '',
        billingAddr: ''
      },
      editAddressData: {
        shopAddr: {},
        billingAddr: {}
      },
      note: '',
      searchProductName: '',
      ipayButtonLoading: false,
      isConLoading: false,
      isLoading: false,
      showNeedPay: false,
      showConfirmOrderSuess: false,
      ShowEditDealerBillingAddress: false,
      ShowEditDealerShoppingAddress: false,
      total: 0,
      orderChart: ''
    }
  },
  created() {
    this.getCompanyInfo()
    this.getShopCart()
    this.getSetMsg()
  },
  mounted() {
  },
  methods: {
    changeNew() {
      this.$forceUpdate()
    },
    searchProduct() {
      if (this.searchProductName) {
        if (this.searchProductName.length > 0) {
          this.$router.push({
            name: 'queryShop',
            params: {
              id: this.searchProductName
            }
          })
        }
      }
    },
    getCompanyInfo() {
      dealer_query_oneApi().then(res => {
        this.detailData = res.data
        if (this.detailData.shopAddr == null || this.detailData.shopAddr == undefined) {
          this.detailData.shopAddr = {}
        }
        if (this.detailData.billingAddr == null || this.detailData.billingAddr == undefined) {
          this.detailData.billingAddr = {}
        }
      }).catch(err => {
        this.$message.error('Alamat tidak didapati')
        this.detailData = []
        console.log(err)
      })
    },
    editAddress(num) {
      switch (num) {
        case 1:
          this.editAddressData.shopAddr = {}
          this.ShowEditDealerBillingAddress = true
          this.editAddressData.billingAddr = this.detailData.billingAddr
          break
        case 2:
          this.editAddressData.billingAddr = {}
          this.ShowEditDealerShoppingAddress = true
          this.editAddressData.shopAddr = this.detailData.shopAddr
          break
      }
    },
    saveMsg() {
      localStorage.setItem('saveMsg', this.note)
    },
    getSetMsg() {
      const saveMsg = localStorage.getItem('saveMsg') ? localStorage.getItem('saveMsg') : null
      if (saveMsg) {
        this.note = saveMsg
      }
      localStorage.removeItem('saveMsg')
    },
    saveDataNow(num) {
      editaddrDealerApi(this.editAddressData, num).then(res => {
        this.$message({
          message: 'Berjaya',
          type: 'success'
        })
        this.saveMsg()
        this.$router.replace({ path: '/redirect' + this.$route.fullPath })
      }).catch(err => {
        console.log(err)
      })
    },
    newOrderClick() {
      this.isLoading = true
      const requestData = {
        detail: this.tableData,
        orderMsg: {
          buyerMsg: this.note
        }
      }
      order_newApi(requestData).then(res => {
        this.$message({
          message: 'success',
          type: 'success'
        })
        this.showNeedPay = false
        this.showConfirmOrderSuess = true
        this.isLoading = false
        this.isConLoading = true
      }).catch(err => {
        console.log(err)
        this.isLoading = false
        this.isConLoading = false
      })
    }, // 得到数据表格
    makePayment() {
      this.isConLoading = true
      if (this.role == this.dealerValue) {
        dealer_query_oneApi().then(res => {
          const resData = res.data
          console.log(resData)
          if (resData.needPay == 1) {
            this.isLoading = true
            this.showNeedPay = true
          } else {
            this.newOrderClick()
          }
        }).catch(err => {
          console.log(err)
        })
      } else {
        this.newOrderClick()
      }
    },
    dealerNewOrder() {
      let _this = this
      this.ipayButtonLoading = true
      const requestData = {
        detail: this.tableData,
        orderMsg: {
          buyerMsg: this.note
        }
      }
      order_newApi(requestData).then(res => {
        if (res.data.MerchantCode && res.data.UserName) {
          this.payData = res.data
          // document.getElementById('ePayment').submit()
          setTimeout(function() {
            _this.$refs.ePayment.submit()
          }, 233)
        }
      }).catch(err => {
        console.log(err)
        this.ipayButtonLoading = false
        this.isLoading = false
        this.isConLoading = true
      })
    },
    handleDel(item) {
      const requestData = {
        'productId': item.productId,
        'quantity': item.quantity
      }
      order_delcartApi(requestData).then(res => {
        this.getShopCart()
      }).catch(err => {
        console.log(err)
      })
    },
    changeQuantity(row) {
      order_editcartApi({ productId: row.productId, quantity: row.quantity }).then(res => {
        this.$message({
          message: 'Berjaya ubah!',
          type: 'success'
        })
        this.getShopCart()
      }).catch(err => {
        this.getShopCart()
        console.log(err)
      })
    },
    getShopCart() {
      order_querycartApi().then(res => {
        this.tableData = res.data
        this.total = 0
        if (res.data) {
          if (res.data.length) {
            if (res.data.length > 0) {
              this.tableData = res.data
              for (let i = 0; i < res.data.length; i++) {
                this.total = this.total + res.data[i].total
              }
            }
          }
        }
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .head-big-title{
    text-align: left;
    font-size: 20px;
    margin: 20px 0 0 3%;
  }
  .dashboard-container{
    margin-top: 20px;
    text-align: center;
  }
  .big-title{
    text-align: left;
  }
  .two-info{
    display: block;
    text-align: left;
    line-height: 28px;
    i{
      width: 21px;
    }
  }
  .title{
    text-align: left;
    line-height: 27px;
  }
  .one-hang{
    display: block;
    width: 100%;
    margin: 0;
    .el-input{
      width: 98%;
    }
    .el-select{
      width: 98%;
    }
  }
  .two-hang{
    display: inline-block;
    width: 50%;
    margin: 0;
    .el-input{
      width: 96%;
    }
    .el-select{
      width: 96%;
    }
  }
  .submit-button{
    display: none;
    width: 88px;
    height: 36px;
    border-radius: 10px;
    border: 2px solid #1482f0;
    background-color: #1482f0;
    color: white;
  }
</style>
<style scoped>
  /deep/.head-search label{
    line-height: 30px;
  }
  .total-sum-div .middle-info{
    text-align: left;
  }
  .total-sum-div .middle-info label{
    display: inline-block;
    width: 120px;
  }
  .total-sum-div .middle-info span{
    display: inline-block;
    width: 66px;
  }
  /deep/.el-dialog{
    width: 80%;
  }
</style>
